#include "StdThread.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define BUFFERSIZE 5
#define ProCount 3
#define ConCount 2

int buffer[BUFFERSIZE]; //缓冲区
Mutex *m;
Cond *notFull; //缓冲区不满
Cond *notEmpty; //缓冲区不空
int count = 0; //缓冲区产品数量计数器

//生产者
void* producer(void*arg)
{   
    long id = (long)arg;
    while(1)
    {
       MutexLock(m);
       while(count == BUFFERSIZE) //缓冲区满
       {
           //放开锁，等待不满的信号
           CondWait(notFull,m);
       }
       int item = rand()%100;
       buffer[count++] = item; //生成一个随机数放入缓冲区
       printf("生产者|%ld|生成数据：%d当前缓冲区产品数量:%d\n",id,item,count);

       CondSignal(notEmpty);
       MutexUnlock(m);
       sleep(rand()%3); //每个生产者随机睡眠

    }
    return NULL;
}

//消费者
void* costumer(void* arg)
{   
    long id = (long)arg;
    while(1)
    {
        MutexLock(m);
        while(count == 0) //缓冲区为空
        {
            CondWait(notEmpty,m);
        }
        printf("消费者|%ld|消费数据:%d,当前缓冲区还剩%d个产品\n",id,buffer[count-1],count-1);
        count--;
        CondSignal(notFull);
        MutexUnlock(m);
        sleep(rand() % 3);
    }
    return NULL;
}

int main()
{   
    m = MutexInit();
    notFull = CondInit();
    notEmpty = CondInit();
    
    Thread * pro[ProCount];
    Thread * con[ConCount];
    
    for(long i = 0;i < ProCount;i++)
    {
        pro[i] = ThreadInit(producer,(void*)i);
    }
    
    for(long i = 0;i < ConCount;i++)
    {
        con[i] = ThreadInit(costumer,(void*)i);
    }
    
     for(long i = 0;i < ProCount;i++)
    {
        ThreadJoin(pro[i]);
    }

     for(long i = 0;i < ConCount;i++)
    {
        ThreadJoin(con[i]);
    }



    ClearMutex(m);
    ClearCond(notFull);
    ClearCond(notEmpty);
    return 0;
}